package com.gjy.sb.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.Semaphore;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-04 17:16:45
 */
@Component
public class SemaphoreInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(SemaphoreInterceptor.class);
    private final Semaphore semaphore = new Semaphore(10);

    @Override
    @SuppressWarnings("all")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("SemaphoreInterceptor preHandle: {}", LocalDateTime.now());
        if (semaphore.availablePermits() == 0) {
            log.error("查过最大并发数,稍后再试");

            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write("查过最大并发数,稍后再试");
            return false;
        } else {
            semaphore.acquire();
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("SemaphoreInterceptor postHandle: {}", LocalDateTime.now());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("SemaphoreInterceptor afterCompletion: {}", LocalDateTime.now());
        semaphore.release();
    }
}
